#!/usr/bin/env python
#coding=utf-8
#import time
import re
import urllib
import DBConn
from BeautifulSoup import BeautifulSoup
class Borad(object):

    def __init__(self,URL):
        self._URL = URL
        
    def GetURL(self):
        return self._URL
    
    def getDBborad(self):
        return DBConn.DBConn().SelectData('select * from borad_data')

    def SyncAllBorad(self):
        sock = urllib.urlopen(self._URL) 
        _html = sock.read() 
        sock.close()
        soup = BeautifulSoup(_html)  
        link = soup.findAll('a',href=re.compile('^/forum/bbs.aspx*'))
        DBborad = self.getDBborad()
        for alink in link:
            find = False
            value = alink.string
            name = alink["href"][22:]
            for k,v in DBborad:
                if (k == name):
                    find = True
                    if(v!=value):
                        sqltext = "update borad_data set msg_boradname = '"+ value + "' where msg_boradid = '"+name+"'"
                        DBConn.DBConn().ExecSQL(sqltext)
                    break
            if (find == False):
                sqltext = "insert into borad_data(msg_boradid,msg_boradname) values('"+ name +"','"+value+"')"
                DBConn.DBConn().ExecSQL(sqltext)       
    def GetRootTreeNodes(self,boradID,page=1):
        sqlText = "select msg_id,msg_parentid,msg_baseid,msg_title,msg_author,msg_readtimes,msg_time,msg_content_words,msg_content,msg_image from main_data "
        sqlText = sqlText+"where msg_baseid in (select msg_baseid from( select msg_baseid, max(msg_id) as flast from main_data where msg_boradid = '"+boradID+"' group by msg_baseid order by flast desc limit "
        int_m = (page-1)*10
        sqlText = sqlText+str(int_m)
        sqlText = sqlText+",10)) order by msg_baseid desc"
        sqlText = "select a.msg_id,a.msg_parentid,a.msg_baseid,a.msg_title,a.msg_author,a.msg_readtimes,a.msg_time,a.msg_content_words,a.msg_content,a.msg_image from main_data a left join (select msg_baseid from( select msg_baseid, max(msg_id) as flast from main_data where msg_boradid = '"+boradID+"' group by msg_baseid order by flast desc limit "+str(int_m)+",11)) b on a.msg_baseid=b.msg_baseid where b.msg_baseid is not null order by a.msg_baseid desc, b.msg_baseid asc"
        a = DBConn.DBConn().SelectData(sqlText)
        return  a
    
    
    
    